﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Design;
using CONSaver_2;

namespace CONSaver_2
{
    public partial class frmMain : Form
    {

        //FTP Settings Struct
        public struct FTPSettingsStruct
        {
            public string IPAddress { get; set; }
            public string User { get; set; }
            public string Password { get; set; }
            public int Port { get; set; }
            public bool Passive { get; set; }
        }

        //Create Variables
        public FTPSettingsStruct FTPSettings = new FTPSettingsStruct(); //Holds FTP Settings
        bool FTPConnected = false;
        X360code x360codeFunctions = new X360code();

        public frmMain()
        {
            InitializeComponent();
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            //Set the form title
            this.Text = "CONSaver " + this.ProductVersion.Substring(0, this.ProductVersion.Length - 4) + " Development";

            //SetFTPStatus("No FTP Connection", CONSaver_2.Properties.Resources.RedFTP);
            //Load Settings file
            
            //Check the file exists before trying to open
            if (File.Exists("Settings.ini"))
            {
                //Try/Catch Block
                try
                {
                    //Create DataTable to hold read values
                    DataTable dt = new DataTable();
                    //Open File
                    using (TextReader tr = File.OpenText("Settings.ini"))
                    {
                        //Variable
                        string line;
                        
                        //While not End Of File
                        while ((line = tr.ReadLine()) != null)
                        {
                            //Split the string into an array, using '=' as the delimiter
                            string[] items = line.Split('=');

                            if (dt.Columns.Count == 0)
                            {
                                // Create the data columns for the data table based on the number of items
                                // on the first line of the file
                                for (int i = 0; i < items.Length; i++)
                                    dt.Columns.Add(new DataColumn("Column" + i, typeof(string)));
                            }
                            //Add data item into DataTable
                            dt.Rows.Add(items);
                        }


                        //Go through DataTable to load settings into variables, removing spaces at the start of each item
                        for (int i = 0; i < dt.Rows[0].Table.Rows.Count; i++)
                        {
                            if (dt.Rows[0].Table.Rows[i].ItemArray[0].ToString().Contains("ip address"))
                                FTPSettings.IPAddress = dt.Rows[0].Table.Rows[i].ItemArray[1].ToString().Remove(0, 1);
                            else if (dt.Rows[0].Table.Rows[i].ItemArray[0].ToString().Contains("username "))
                                FTPSettings.User = dt.Rows[0].Table.Rows[i].ItemArray[1].ToString().Remove(0, 1);
                            else if (dt.Rows[0].Table.Rows[i].ItemArray[0].ToString().Contains("password"))
                                FTPSettings.Password = dt.Rows[0].Table.Rows[i].ItemArray[1].ToString().Remove(0, 1);
                            else if (dt.Rows[0].Table.Rows[i].ItemArray[0].ToString().Contains("port"))
                                FTPSettings.Port = int.Parse(dt.Rows[0].Table.Rows[i].ItemArray[1].ToString().Remove(0, 1));
                            else if (dt.Rows[0].Table.Rows[i].ItemArray[0].ToString().Contains("passive"))
                                FTPSettings.Passive = Convert.ToBoolean(dt.Rows[0].Table.Rows[i].ItemArray[1].ToString().Remove(0, 1));
                        }
                    }
                }
                catch 
                {

                }
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            //create OpenFileDialog instance
            OpenFileDialog oFileDialogInstance = new OpenFileDialog();

            //Set OpenFileDialog Properties
            oFileDialogInstance.CheckFileExists = true;
            oFileDialogInstance.InitialDirectory = Environment.SpecialFolder.MyDocuments.ToString();
            oFileDialogInstance.CheckFileExists = false;
            oFileDialogInstance.CheckPathExists = false;
            oFileDialogInstance.Title = "Select Content Path:";
            FolderBrowserDialog oDir = new FolderBrowserDialog();

            oDir.RootFolder = Environment.SpecialFolder.MyDocuments;
            if (oDir.ShowDialog() == DialogResult.OK)
            {
                
                bckgrndWorkerScanFiles.RunWorkerAsync(oDir.SelectedPath);
            }
            
            
            //oFileDialogInstance.

            //If User selects a file and clicks ok
            //if (oFileDialogInstance.ShowDialog() == DialogResult.OK)
            //{

            //}
        }

        private void btnRemove_Click(object sender, EventArgs e)
        {
            if (listViewGameSaves.SelectedItems.Count != 0)
            {
                
                foreach(ListViewItem selectedItem in listViewGameSaves.SelectedItems)
                {
                    listViewGameSaves.Items[selectedItem.Index].Remove();
                }
            }
        }

        private void RecursiveScan(string pathToScan)
        {
            DirectoryInfo Dir = new DirectoryInfo(pathToScan);

            foreach (FileInfo fileFound in Dir.GetFiles("*.*"))
            {
                //check if CON file
                if (fileFound.Extension != ".bak")
                 AddToList(fileFound.FullName);
            }

            foreach (DirectoryInfo DirFound in Dir.GetDirectories())
            {
                RecursiveScan(DirFound.FullName);
            }

        }

        private void AddToList(string Path)
        {
            FileScan FileScanCode = new FileScan();
            string GameName = null;
            string FileType = null;
            string FlaggedArea = null;
            string SaveFileName = null;
            string ProfileID = null;
            string DeviceID = null;
            string ConsoleID = null;

            int index = listViewGameSaves.Items.Count;
            FileType = FileScanCode.GetTypeFile(Path);

            GameName = FileScanCode.GetGameName(Path, FileType);
            SaveFileName = FileScanCode.GetFilename(Path);
            FlaggedArea = FileScanCode.GetFlaggedArea(Path);
            ProfileID = x360codeFunctions.ExtractProfileID(Path);
            DeviceID = FileScanCode.GetDeviceID(Path);
            ConsoleID = FileScanCode.GetConsoleID(Path);
            //DeviceID = x360codeFunctions.ExtractProfileID(Path).ToString();
                
            //GameName
            listViewGameSaves.Items.Add(GameName);
            //Type
            listViewGameSaves.Items[index].SubItems.Add(FileType);
            //Flagged Area
            listViewGameSaves.Items[index].SubItems.Add(FlaggedArea);
            //Location
            listViewGameSaves.Items[index].SubItems.Add(Path);
            //Save File Name
            listViewGameSaves.Items[index].SubItems.Add(SaveFileName);
            //Profile ID
            listViewGameSaves.Items[index].SubItems.Add(ProfileID);
            //Device ID
            listViewGameSaves.Items[index].SubItems.Add(DeviceID);
            //Console ID
            listViewGameSaves.Items[index].SubItems.Add(ConsoleID);
        }

        private void selectAllToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem ListItem in listViewGameSaves.Items)
            {
                
                ListItem.Selected = true;
            }
        }

        private void bckgrndWorkerScanFiles_DoWork(object sender, DoWorkEventArgs e, string pathToScan)
        {

            DirectoryInfo Dir = new DirectoryInfo(pathToScan);

            foreach (FileInfo fileFound in Dir.GetFiles("*.*"))
            {
                //check if CON file
                if (fileFound.Extension != ".bak")
                 AddToList(fileFound.FullName);
            }

            foreach (DirectoryInfo DirFound in Dir.GetDirectories())
            {
                RecursiveScan(DirFound.FullName);
            }

        }
        

    }
}
